import { findSubCategoryGoods } from '@/api/category'
import { ref } from 'vue'
import { useRoute } from 'vue-router'

export function toggleData () {
  const route = useRoute()
  function toggleSelected (list, obj) {
    list.properties.forEach((itm) => {
      itm.selected = false
    })
    obj.selected = true
    const inx = reqParams.attrs.findIndex(itm => itm.groupName === list.name)
    if (inx > -1) {
      reqParams.attrs.splice(inx, 1)
    }
    reqParams.attrs.push({
      groupName: list.name,
      propertyName: obj.name
    })
    if (obj.id === null) {
      const inx = reqParams.attrs.findIndex(itm => itm.groupName === list.name)
      if (inx > -1) {
        reqParams.attrs.splice(inx, 1)
      }
    }
    reqParams.page = 1
    isFedir.value = true
    loadData()
  }
  function toggle (list, obj) {
    list.forEach((itm) => {
      itm.selected = false
    })
    obj.selected = true
    reqParams.brandId = obj.id
    reqParams.page = 1
    isFedir.value = true
    loadData()
  }

  const sorTypeListRef = ref([
    { name: '默认排序', value: null },
    { name: '最新商品', value: 'publishTime' },
    { name: '最高人气', value: 'orderNum' },
    { name: '评论最多', value: 'evaluateNum' }
  ])
  const curSortTypeRef = ref(null)
  function toggleSort (val) {
    curSortTypeRef.value = val
    reqParams.sortField = val
    reqParams.page = 1
    isFedir.value = true
    loadData()
  }
  const goodList = ref([])
  // 请求参数
  const reqParams = {
    page: 0,
    pageSize: 20,
    categoryId: route.params.id,
    sortField: null, // 排序类别
    attrs: [], // 商品属性
    brandId: null // 品牌名称
  }
  async function loadData () {
    const res = await findSubCategoryGoods(reqParams)
    goodList.value = res.result.items
  }
  // onMounted(() => {
  //   loadData()
  // })
  const isFedir = ref(true)
  const isLoad = ref(true)
  async function subPage () {
    reqParams.page++
    isLoad.value = false
    const res = await findSubCategoryGoods(reqParams)
    isLoad.value = true
    if (res.result.items.length === 0) {
      isFedir.value = false
    }
    goodList.value = [...goodList.value, ...res.result.items]
  }
  return {
    toggleSelected,
    toggle,
    sorTypeListRef,
    toggleSort,
    curSortTypeRef,
    goodList,
    subPage,
    isFedir,
    isLoad
  }
}
